from venvrecipes import utils
import os
import pkg_resources
import sys

REQ = pkg_resources.Requirement.parse('VenvRecipe')
path_join = os.path.join

# rewrite as an extension ala gp.svndevelop

class VirtualEnvCompat(object):
    
    def __init__(self, buildout, name, options):
        self.name, self.options = name, options
        self.buildout = buildout
        self.venv = os.environ.get('VIRTUAL_ENV')
        self.use_env = buildout['virtualenv'].get('use-env', True)
        buildout['virtualenv']['env_dir']=self.venv
        self.build_name = buildout['virtualenv'].get('build-name', '')
        self.parts_name = "parts"
        if self.build_name:
            self.parts_name = "%s-%s" %(self.build_name,  self.parts_name)
        if self.venv and self.use_env:
            self.path_map = {'bin-directory': '%s/bin' %self.venv,
                             'develop-eggs-directory': '%s/src' %self.venv,
                             'directory': self.venv,
                             'develop-eggs': "%s/develop-eggs" %self.venv,
                             'eggs-directory': self.egg_dir,
                             'parts-directory': '%s/%s' %(self.venv, self.parts_name)}
            for key, val in self.path_map.items():
                buildout['buildout'][key]=val
        else:
            print "Not using virtual env setup"

    @property
    def egg_dir(self):
        """return the site packages for a virtualenv"""
        return (p for p in sys.path if p.endswith('site-packages') \
                and p.startswith(self.venv)).next()

    def install(self):
        """installer"""
        if self.venv and self.use_env:
            fh = [val for val in self.path_map.values()\
                  if utils.safe_mkdir(val)]
            return tuple(fh)
        return tuple()

    def update(self):
        """updater"""
        pass
